var apiHost = wx.getStorageSync("apiHost"); //请求地址

var Appid = wx.getStorageSync('Appid');
var Secret = wx.getStorageSync('Secret');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: false, //是否显示面板指示点（轮播图）
    autoplay: true,       //是否自动切换（轮播图）
    interval: 6000,       //自动切换时间间隔（轮播图）
    duration: 1000,       //滑动动画时长（轮播图）
    floorstatus: false,   //返回顶部按钮是否显示
    scrollTop: 0,         //返回顶部高度
    collageDetail : '',   //拼团详情
    collagePrice : 0 ,    //拼团价格
    progressFlag : '',    //进度条百分比
    shopNum: '1',         //购买数量
    maxBugCount : '1',    //最大购买数量
    showProModelFlag : false, //查看规格弹框
    firstProId :'',
    secondProId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.countDetailBtnCon();//计算拼团详情 高度
    var collageId = options.collageId; //拼团Id
    // var collageId = '3a898964227449409ac5055fd2333a4d'; //拼团Id
    that.initDtail(collageId);//始化 拼团详情

    var openId = wx.getStorageSync('openId');     //用户openId获取
    var userId = wx.getStorageSync('userId');     //用户userId获取

    // 判断openid弹窗授权
    if (openId != '') {
      that.setData({
        openId: openId,
        userId: userId,
        showCancelArea: false
      });
    } else {
      that.setData({
        showCancelArea: true
      });
    }

  },
  /**
   * 初始化 拼团详情
   */
  initDtail: function (collageId){
    var that = this;

    wx.showLoading({
      title: '玩命加载中',
      icon:"loading",
      mask:true
    })

    wx.request({
      url: apiHost +'hpp/collage/detail',
      method: 'GET',
      header : {
        "contenr-type" : "application/json"
      },
      data : {
        collageId: collageId
      },
      success : function(res){
        console.log(res)
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000"){
          var collageDetail = res.data.data;
          var collagePrice = collageDetail.collagePriceVos[0].collagePrice;

          var maxBugCount = collageDetail.maxBugCount;  //一人最多购买数量

          // 计算拼团人数进度条  （100/总拼团人数）* 参团人数
          var progressFlag = (100 / parseInt(collageDetail.requireCount)) * parseInt(collageDetail.joinColage);

          var imagesVideo = collageDetail.imageVieoVos;

          // 拿到分享图片
          for (var i = 0; i < imagesVideo.length;i++){
            if (imagesVideo[i].type=='image'){
              that.setData({
                shareImg: imagesVideo[i].url
              });
            }
          }
          
          that.setData({
            collageDetail: collageDetail,
            collagePrice : collagePrice,
            progressFlag: progressFlag,
            maxBugCount: maxBugCount
          });
          wx.hideLoading();
        }else{
          wx.hideLoading();
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      },
      fail : function(){
        wx.hideLoading();
        wx.showToast({
          title: "网络异常",
          icon: 'none',
          duration: 2000,
          mask: true
        });
      }
    })
  },

  /**
   * 计算拼团详情 高度
   */
  countDetailBtnCon: function () {
    var that = this;
    /*获取指定元素高度*/
    var query2 = wx.createSelectorQuery();
    var detailBtnCon = "";

    query2.select('#detailBtnCon').boundingClientRect()
    query2.exec(function (res) {
      detailBtnCon = res[0].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            goodsDetailsHeight: res.windowHeight - detailBtnCon,
          });
        }
      });
    });
  },

  /**
   * 查看规格弹窗
   */
  showProModel: function(){
    var that =this;
    that.setData({
      showProModelFlag : true
    });
  },
  /**
   * 关闭规格弹窗
   */
  hideProModel:function(){
    var that = this;
    that.setData({
      showProModelFlag: false
    });
  },

  /**
   * 点击规格11
   */
  onclickProValueF:function(e){
    var that = this;
    var numProIdList = e.currentTarget.dataset.toggle
    console.log(numProIdList)
    that.setData({
      firstProId: numProIdList
    });

  },
  /**
   * 点击规格22
   */
  onclickProValueS: function (e) {
    var that = this;
    var numProIdList = e.currentTarget.dataset.toggle
    console.log(numProIdList)

    that.setData({
      secondProId: numProIdList
    });

  },
  
  /**
   * 减购买数量
   */
  shopNumSub :function(){
    var that = this;
    var shopNum = that.data.shopNum;

    if (shopNum!=1){
      shopNum = parseInt(shopNum)-1;
      that.setData({
        shopNum: shopNum
      })
    }else{
      wx.showToast({
        title: "至少购买一个",
        icon: 'none',
        duration: 2000,
        mask: true
      });
    }
  },

  /**
   * 加购买数量
   */
  shopNumAdd: function () {
    var that = this;
    var shopNum = that.data.shopNum;
    var maxBugCount = that.data.maxBugCount;
    
    if (shopNum < maxBugCount) {
      shopNum = parseInt(shopNum)+1;
      
      that.setData({
        shopNum: shopNum
      })
    }else{
      wx.showToast({
        title: "超过最多购买数量",
        icon: 'none',
        duration: 2000,
        mask: true
      });
    }
  },

  /**
   * 跳转提交订单页面
   */
  goPatment : function(e){
    var that = this ; 
    var sendRes = [];                                  //传递参数
    var sendResStr = '';                               //传递参数拼接
    var collageIdNum = e.currentTarget.dataset.toggle; //拼团id

    var collageIdNumList = collageIdNum.split(",");    //拼团id 和 规格数量
    var collageId = collageIdNumList[0];               //拼团id
    var Num = collageIdNumList[1];                     //规格数量

    var firstProId = that.data.firstProId;              //规格1
    var secondProId = that.data.secondProId;            //规格2

    // 判断是否选取规格
    if (Num=="2"){
      if (firstProId=="") {
        that.showMsg("请选择规格");  //提示信息
        return
      }
      if (secondProId == "") {
        that.showMsg("请选择规格");  //提示信息
        return
      }
    } else if (Num == "1"){
      if (firstProId=="") {
        that.showMsg("请选择规格");  //提示信息
        return
      }
    }

    var shopNum = that.data.shopNum;                //购买数量
    var skuIdsStr = firstProId;

    // 判断是否有两个规格
    if (secondProId != '') {
      skuIdsStr = skuIdsStr + ":" + secondProId;
    }
    //拼接传送参数
    sendResStr = '{ "collageId":"' + collageId + '","shopNum":"' + shopNum + '","skuIdsStr":"' + skuIdsStr +'" }';

    wx.showLoading({
      title: '跳转中',
      icon: 'loading',
      mask: true
    });
    wx.reLaunch({
      url: '../ordinaryCollage/payment/payment?sendResStr=' + sendResStr,
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },

  /**
   * 我也要拼团
   */
  goFirstCollage:function(){
    wx.showLoading({
      title: '跳转中',
      icon: 'loading',
      mask: true
    });
    wx.reLaunch({
      url: '../ordinaryCollage/firstOrdinaryCollage/firstOrdinaryCollage',
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },

  /**
   * 返回首页
   */
  goIndex:function(){
    wx.showLoading({
      title: '跳转中',
      icon: 'loading',
      mask: true
    });
    wx.reLaunch({
      url: '../../index/index',
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },

  //监听滑动事件
  scroll: function (e) {
    if (e.detail.scrollTop > 500) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },
  //返回顶部高度
  goTop: function (e) {
    this.setData({
      scrollTop: 0
    })
  },
  /**
   * 提示信息
   */
  showMsg : function(msg){
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000,
      mask: true
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
 * 用户点击右上角分享
 */
  onShareAppMessage: function (options) {
    var that = this;

    var title = options.target.dataset.title;
    var shareImg = that.data.shareImg;
    var collageId = options.target.dataset.collageid;

    console.log(collageId)

    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: title,    // 默认是小程序的名称(可以写slogan等)
      path: 'pages/Collage/collageDetail/collageDetail?collageId=' + collageId,        // 默认是当前页面，必须是以‘/’开头的完整路径
      imgUrl: shareImg,                     //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log("转发成功之后的回调")
        }
      },
      fail: function (res) {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          console.log("用户取消转发")
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          console.log("转发失败")
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
    }
    // 来自页面内的按钮的转发
    　　if (options.from == 'button') {
          // 此处可以修改 shareObj 中的内容
        shareObj.path = 'pages/Collage/collageDetail/collageDetail?collageId=' + collageId;
    　　}
    　　// 返回shareObj
    　　return shareObj;
  },
  //按钮获取用户信息
  bindGetUserInfo: function (res) {
    var that = this;

    var errMsgFlg = res.detail.errMsg

    if ("getUserInfo:ok" == errMsgFlg) {
      var userCon = res.detail
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurlUser(userCon, code)
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    }
  },

  /**
  * 解密用户登录完成后的url
  */
  VERBurlUser: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'hpp/UserInfo/decodeUserInfo',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: Appid,
        Secret: Secret
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果

        if (data.data.status == 1) {
          var userInfo_ = data.data.userInfo;

          var openIdFl = userInfo_.openId;
          var phone = userInfo_.phone;

          that.getuserId(userInfo_.openId);       //获取userId
          wx.setStorageSync('openId', openIdFl);
          wx.setStorageSync('phone', phone);
          wx.setStorageSync('session_token', userInfo_.session_key);
          wx.setStorageSync('userInfo', userInfo_);

          that.setData({
            showCancelArea: false
          });
          that.onLoad();
        } else {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '网络异常',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  /**
   * 获取userId
   */
  getuserId: function (openId) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: "loading",
      mask: true
    });

    wx.request({
      url: apiHost + 'hpp/user/userInfoByOpenId',
      method: 'GET',
      header: {
        "content-type": 'application/json'
      },
      data: {
        openId: openId
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        wx.hideLoading();   //隐藏加载loading
        if ("10000" == code) {

          if (res.data.data.length != 0) {
            var userId = res.data.data.id;
            that.setData({
              userId: userId
            });

            wx.setStorageSync("userId", userId)
          }

        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 5000,
            mask: true
          });
        }
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 5000,
          mask: true
        });
      }
    })
  },
  /**
  * 手机号授权方式
  */
  getPhoneNumberF: function (res) {
    var that = this;
    var errMsgFlg = res.detail.errMsg

    if ("getPhoneNumber:ok" == errMsgFlg) {
      var userCon = res.detail;
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurl(userCon, code)
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {

          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    } else {
      wx.showToast({
        title: '授权后即可购买',
        icon: 'none',
        duration: 2000,
        mask: true
      });
    }
  },

  /**
  * 解密用户登录完成后的url (用户手机号)
  */
  VERBurl: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'hpp/UserInfo/decodePhoneNumber',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: Appid,
        Secret: Secret
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果
        if (data.data.status == 1) {
          var phone = data.data.userInfo.phoneNumber;

          that.reginPhoneOpenid(phone);
        } else {
          wx.showToast({
            title: '解密失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {

        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '系统错误',
          icon: 'none',
          duration: 2000,
          mask: true
        });
      }
    })
  },
  //表单提交
  reginPhoneOpenid: function (userPhone) {
    var that = this;
    var userInfo = wx.getStorageSync('userInfo'); //用户userInfo获取
    var nickName = userInfo.nickName;     //	昵称
    var avatarUrl = userInfo.avatarUrl;   //用户头像
    var openId = that.data.openId;   //openID

    wx.request({
      url: apiHost + "hpp/user/auth",
      data: {
        openId: openId,
        phone: userPhone,
        nickName: nickName,
        avatarUrl: avatarUrl
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res)
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == '10000') {
          that.setData({
            phone: userPhone
          })
          wx.setStorageSync('phone', userPhone);
          var userId = res.data.data.id
          wx.setStorageSync('userId', userId);
          that.publishOrdinaryCollage();//跳转发布
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      },
      fail: function () {
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000,
          mask: true
        });
      }
    });
  },
})